package util;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 有道翻译
 * USER: lintc 【lintiancong@zhuojianchina.com】
 * DATE: 2017/5/25 15:31
 */
public class YouDaoTranslation implements Translation{

    @Override
    public String translation(String word) {
        String translate = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //            String ak = "lVxrccdqXqrXuG5PCT8kWKhudNSjSPcg";
            HttpGet httpget = new HttpGet("http://dict-co.iciba.com/api/dictionary.php?w="
                    + word
                    + "&type=json&key=24488AD4E17AF9ED3B33680B8CCA4C46");
            //            httpget.addHeader(new BasicHeader("ip", ip));
            // httpget.addHeader("", "");
            CloseableHttpResponse httpReponse = httpClient.execute(httpget);
            try {
                //                System.out.println(httpReponse.getStatusLine());
                HttpEntity entity = httpReponse.getEntity();
                String s = EntityUtils.toString(entity, "utf-8");

//                System.out.println(s);
                JSONObject obj = JSONObject.fromObject(s);
                obj = (JSONObject) obj.optJSONArray("symbols").get(0);
                translate = obj.optJSONArray("parts").toString();
            } finally {
                httpReponse.close();
            }
        } catch (Exception e) {
        }
        return translate;
    }

    public static void main(String[] args) {
        Translation youdao = new YouDaoTranslation();
        System.out.println(youdao.translation("translation"));
    }
}
